#include "framebufferhandler.h"
#include <iostream>

using namespace std;

FramebufferHandler::FramebufferHandler () {
    this->current = 0;
    this->defaultFramebuffer = NULL;
}

FramebufferHandler::~FramebufferHandler () {
    if (this->defaultFramebuffer != NULL) {
        delete this->defaultFramebuffer;
    }
    
    for (unsigned int i=0; i< this->buffers.size(); i++) {
        delete this->buffers.at(i);
    }
}

void FramebufferHandler::addBuffer (Framebuffer *framebuffer, bool def) {
    
    if (def) {
        this->defaultFramebuffer = framebuffer;
    } else {
        this->buffers.push_back(framebuffer);    
    }
    
}

void FramebufferHandler::bindFirst (bool def) {
    this->current = 0;
    this->bind(def);
}

void FramebufferHandler::bindNext (bool def) {
    unsigned int size = this->buffers.size();
    
    if (size == 0) {
        cerr << "FramebufferHandler::bindNext: no framebuffers added" << endl;
        return;
    }
    
    if (!def) {
        this->current = (this->current+1) % size;
    }
    
    this->bind(def);
}

void FramebufferHandler::bind (bool def) {
    int size = this->buffers.size();
    
    if (size == 0) {
        cerr << "FramebufferHandler::bind: no framebuffers added" << endl;
        return;
    }    
    
    if (def) {
        if (this->defaultFramebuffer != NULL) {
            this->defaultFramebuffer->bind();
        } else {
            cerr << "FramebufferHandler::bind: no default framebuffer" << endl;    
        }
    } else {
        this->buffers.at(this->current)->bind();
    }
    
    this->bindTextures(def);
}

/**
 * Calls previous framebuffer bindTextures method
 * 
 * @param bool def - use default framebuffer
 */
void FramebufferHandler::bindTextures(bool def) {
    unsigned int previous = 0;
    
    if (def) {
        previous = this->current;
    } else {
        unsigned int size = this->buffers.size();
        previous = (this->current+1) % size;        
    }
    
    this->buffers.at(previous)->bindTextures();
}

void FramebufferHandler::resizeTextures (int width, int height) {
    if (this->defaultFramebuffer != NULL) {
        this->defaultFramebuffer->resizeTextures(width, height);
    }
    
    for (unsigned int i=0; i< this->buffers.size(); i++) {
        this->buffers.at(i)->resizeTextures(width, height);
    }
}